<template>
  <div class="incomesDetial">
    <div v-if="detailType == false">
      <div class="summaryheader">
        <div class="shareheader_top">
          <div style="min-width: 260px; margin: 0px 10px 18px 0px">
            <span style="font-size: 13px; padding: 0px 8px 0px 0px">客户:</span>
            <el-select
              v-model="orderSearch.customer_id"
              filterable
              placeholder="请选择所属客户"
              style="width: 200px; padding: 0px 8px 0px 0px"
            >
              <el-option
                v-for="(item, index) in customerBoxData"
                :key="index"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </div>
          <div style="min-width: 260px; margin: 0px 10px 18px 0px">
            <span style="font-size: 13px; padding: 0px 8px 0px 0px"
              >客户所属区域:</span
            >
            <el-select
              v-model="orderSearch.customer_area_id"
              placeholder="客户所属区域"
              filterable
              style="width: 200px; padding: 0px 8px 0px 0px"
            >
              <el-option
                v-for="website in websiteList"
                :key="website.id"
                :label="website.name"
                :value="website.id"
              />
            </el-select>
          </div>
          <div style="min-width: 260px; margin: 0px 10px 18px 0px">
            <span style="font-size: 13px; padding: 0px 8px 0px 0px"
              >创建订单时间:</span
            >
            <el-date-picker
              v-model="datepicker"
              type="daterange"
              :default-time="['00:00:00', '23:59:59']"
              range-separator="至"
              value-format="timestamp"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
            >
            </el-date-picker>
          </div>
          <div style="min-width: 100px; margin: 0px 10px 18px 0px">
            <el-button type="primary" icon="el-icon-search" @click="onSubmit()"
              >查询</el-button
            >
            <el-button
              type="primary"
              plain
              class="improtOut"
              icon="el-icon-search"
              @click="reSet()"
              >重置</el-button
            >
          </div>
        </div>
      </div>
      <div
        class="sharecontent_headr"
        style="margin-bottom: 10px; overflow: hidden; height: 30px"
      >
        <el-button
          v-permission="'report_form_revenue_cost_summary_export'"
          type="primary"
          plain
          class="improtOut"
          :loading="loadingtype"
          @click="ExportClickPlayFn"
        >
          导出
        </el-button>
      </div>
      <div>
        <el-table
          :data="tableData"
          ref="table"
          style="width: 100%"
          um-text="汇总"
          show-summary
          :summary-method="getSummaries"
          fixed
          height="480"
          border
        >
          <el-table-column
            prop="customer_area_name"
            label="客户所属区域"
            width="200"
          >
          </el-table-column>
          <el-table-column prop="customer_name" label="客户" width="200">
            <template slot-scope="scope">
              <span
                style="color: #409eff; cursor: pointer"
                @click="client(scope.row.customer_id)"
                >{{ scope.row.customer_name }}</span
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="freight"
            label="运单总运费"
            width="100"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="w_account_ratio"
            label="对账占比"
            width="80"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="total_cost"
            label="总成本"
            width="100"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="gross_profit"
            label="毛利润"
            width="100"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="gross_profit_margin"
            label="毛利率"
            width="100"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="collect_money"
            label="揽收总费用"
            width="100"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="l_account_ratio"
            label="揽收对账占比
          "
            width="100"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="transport_money"
            label="运输总费用"
            width="100"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="g_account_ratio"
            label="
          运输对账占比"
            width="100"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="distribution_money"
            label="配送总费用"
            width="100"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="p_account_ratio"
            label="
          配送对账占比"
            width="100"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="receipt_money"
            label="回单总费用"
            width="100"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="hd_account_ratio"
            label="
          回单对账占比"
            width="100"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="box_recycle_money"
            label="回箱总费用"
            width="100"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="hx_account_ratio"
            label="
          回箱对账占比"
            width="100"
            align="right"
          >
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div v-if="detailType == true">
      <incomesdetial :detailTime="detailTime" :detailId="detailId" />
    </div>
  </div>
</template>
<script>
import incomesdetial from "./components/incomesdetial.vue";
import {
  branchList,
  customerBox,
  incomeCost, // 收入成本汇总
  summaryExport, // 收入成本汇总导出
} from "@/api/Largewidthmeterlist";
import { nearer } from "q";
export default {
  name: "reimburSement",
  components: {
    incomesdetial,
  },
  data() {
    return {
      orderSearch: {
        customer_id: "",
        customer_area_id: "",
        start_time: "",
        end_time: "",
      },
      datepicker: [],
      loadingtype: false,
      detailType: false,
      detailName: "",
      detailId: "",
      customerBoxData: [],
      websiteList: [],
      tableData: [],
    };
  },

  mounted() {
    // 客户接口
    this.customerBoxFn();
    // 客户所属区域
    this.getWebsiteList();

    // 调用创建
    this.lastMonthTimetamp();
  },
  updated() {
    // this.$nextTick(() => {
    //   this.$refs["table"].doLayout();
    // });
    setTimeout(() => {
      this.$refs["table"].doLayout();
    }, 100);
  },
  methods: {
    // 查询
    onSubmit() {
      this.incomeCostObj();
    },
    //获取所属客户
    customerBoxFn() {
      let data = {
        name: "", //名称
        is_send: "1", //是否为客户 0不  1是客户
        is_receive: "", //是否收货单位  0不是  1是
      };
      customerBox(data).then((res) => {
        if (res.code === 10000) {
          this.customerBoxData = res.data;
        }
      });
    },
    // 客户所属区域
    async getWebsiteList() {
      let result = await branchList({ branch_type: "3" });
      this.websiteList = result.data;
    },
    // 导出
    ExportClickPlayFn() {
      this.loadingtype = true;
      var param = {
        customer_id: this.orderSearch.customer_id + "",
        customer_area_id: this.orderSearch.customer_area_id + "",
        start_time:
          this.datepicker.length > 0 ? this.datepicker[0] / 1000 + "" : "",
        end_time:
          this.datepicker.length > 0 ? this.datepicker[1] / 1000 + "" : "",
      };
      summaryExport(param).then((res) => {
        if (res.code == 10000) {
          this.loadingtype = false;
          var loadedurl = "https://" + res.data.loaded_url;
          window.open(loadedurl);
        } else {
          this.loadingtype = true;
          this.$message.error("数据导出失败");
        }
      });
    },
    //
    incomeCostObj() {
      var param = {
        customer_id: this.orderSearch.customer_id + "",
        customer_area_id: this.orderSearch.customer_area_id + "",
        start_time: this.datepicker[0] / 1000 + "",
        end_time: this.datepicker[1] / 1000 + "",
      };
      incomeCost(param).then((res) => {
        this.tableData = res.data.data;
      });
    },
    reSet() {
      this.lastMonthTimetamp();
      this.orderSearch.customer_id = "";
      this.orderSearch.customer_area_id = "";
      this.incomeCostObj();
    },
    client(id) {
      // console.log(id, "id");
      this.detailId = id;
      this.detailTime = this.datepicker;
      this.detailType = true;
    },
    // 子组件调用关闭函数
    clientclose() {
      this.detailName = "";
      this.detailId = "";
      this.detailType = false;
    },
    lastMonthTimetamp() {
      //  一天的秒数
      const MillisecondsADay = 24 * 60 * 60;

      const date = new Date();
      date.setDate(1);
      date.setHours(0, 0, 0, 0);
      //  当月开始时间戳
      const timeStamp = date.getTime() / 1000;
      //  上个月的天数
      const days = this.lastMonthDats();
      //  上月开始时间戳
      const lastMonthStart = timeStamp - MillisecondsADay * days;
      //  上月结束时间戳
      const lastMonthEnd = timeStamp - 1;
      this.datepicker = [lastMonthStart * 1000, lastMonthEnd * 1000];
      // 客户
      this.incomeCostObj();
    },
    lastMonthDats() {
      const date = new Date();
      const year = date.getFullYear();
      //  上个月月份
      let month = date.getMonth() + 1 - 1; //  0-11 表示 1月-12月
      //  0 表示12月
      month = month || 12;
      //  30天的月份
      const arr30 = [4, 6, 9, 11];
      //  31天的月份
      const arr31 = [1, 3, 5, 7, 8, 10, 12];
      if (arr30.indexOf(month) !== -1) {
        //  上个月是 30 天
        return 30;
      } else if (arr31.indexOf(month) !== -1) {
        //  上个月是 31 天
        return 31;
      } else {
        //  2月
        if (this.isRunYear(year)) {
          return 29;
        } else {
          return 28;
        }
      }
    },
    getSummaries(param) {
      // console.log(param, "paammmmmmm ");
      const { columns, data } = param;
      const sums = {};
      columns.forEach((column) => {
        sums[column.property] = 0;
      });
      // 对账占比
      var Allalreadycount = 0; //已经对账的
      var Alltotalcount = 0; //总数
      // 总运费
      var Allfreight = 0; //总运费
      // 总毛利润
      var AllgrossProfit = 0; // 总毛利润
      // 揽收占比
      var All_l_total_count = 0; // 揽收总数
      var All_l_already_count = 0; // 已对账数
      // 运输占比
      var All_g_total_count = 0;
      var All_g_already_count = 0;
      // 配送占比
      var All_p_total_count = 0;
      var All_p_already_count = 0;
      // 回单对账占比
      var All_hd_total_count = 0;
      var All_hd_already_count = 0;
      // 回想占比
      var All_hx_total_count = 0;
      var All_hx_already_count = 0;
      data.forEach((item) => {
        columns.forEach((column, index) => {
          if (column.property in sums) {
            if (column.property === "freight") {
              if(item.freight != "") {
                sums[column.property] += parseFloat(item.freight);
              }
            
            } else if (column.property === "w_account_ratio") {
               if( item.w_already_count != "") {
                Allalreadycount += parseFloat(item.w_already_count);
               }
              if(item.w_total_count != "") {
                Alltotalcount += parseFloat(item.w_total_count);
              } 
              sums[column.property] =
                (Allalreadycount / Alltotalcount).toFixed(2) * 100 + "%";
            } else if (column.property === "total_cost") {
              if(item.total_cost != "") {
                sums[column.property] += parseFloat(item.total_cost);
              }
          
            } else if (column.property === "gross_profit") {
              if(item.gross_profit != "") {
                sums[column.property] += parseFloat(item.gross_profit);
              }

            } else if (column.property === "gross_profit_margin") {
              if(item.freight != "") {
                Allfreight += parseFloat(item.freight);
              }
              if(item.gross_profit != "") {
                AllgrossProfit += parseFloat(item.gross_profit);
              }

              sums[column.property] =
                (AllgrossProfit / Allfreight).toFixed(2) * 100 + "%";
            } else if (column.property === "collect_money") {
              if( item.collect_mone != "") {
                sums[column.property] += parseFloat(item.collect_money);
              }
            } else if (column.property === "l_account_ratio") {
              if( item.l_total_count != "") {
                All_l_total_count += parseFloat(item.l_total_count);
              }
              if(item.l_already_count != "") {
                All_l_already_count += parseFloat(item.l_already_count);
              }

              sums[column.property] =
                (All_l_already_count / All_l_total_count).toFixed(2) * 100 +
                "%";
            } else if (column.property === "transport_money") {
               if(item.transport_money != '' ) {
                sums[column.property] += parseFloat(item.transport_money);
               }
  
            } else if (column.property === "g_account_ratio") {
              if( item.g_total_count != "") {
                All_g_total_count += parseFloat(item.g_total_count);
              }
              if(item.g_already_count) {
                All_g_already_count += parseFloat(item.g_already_count);
              }

              sums[column.property] =
                (All_l_already_count / All_l_total_count).toFixed(2) * 100 +
                "%";
            } else if (column.property === "distribution_money") {
              if(item.distribution_money != "") {
                sums[column.property] += parseFloat(item.distribution_money);
              }

            } else if (column.property === "p_account_ratio") {
              if(item.p_total_count != " ") {
                All_p_total_count += parseFloat(item.p_total_count);
              }
              if(item.p_already_count != "") {
                All_p_already_count += parseFloat(item.p_already_count);
              }

              if (All_p_total_count != 0) {
                sums[column.property] =
                  (All_p_already_count / All_p_total_count).toFixed(2) * 100 +
                  "%";
              } else {
                sums[column.property] = 0 + "%";
              }
            } else if (column.property === "receipt_money") {
              if(item.receipt_money != '') {
                sums[column.property] += parseFloat(item.receipt_money);
              }

            } else if (column.property === "hd_account_ratio") {
              if(item.hd_total_count != '' ) {
                All_hd_total_count += parseFloat(item.hd_total_count);
              }
              if(item.hd_already_count != '') {
                All_hd_already_count += parseFloat(item.hd_already_count);
              }

              sums[column.property] =
                (All_hd_already_count / All_hd_total_count).toFixed(2) * 100 +
                "%";
            } else if (column.property === "box_recycle_money") {
              if(item.box_recycle_money != '') {
                sums[column.property] += parseFloat(item.box_recycle_money);
              }

            } else if (column.property === "hx_account_ratio") { 
              if(item.hx_total_count != '') {
                All_hx_total_count += parseFloat(item.hx_total_count);
              }
              if(item.hx_already_count != '') {
                All_hx_already_count += parseFloat(item.hx_already_count);
              }

              sums[column.property] =
                (All_hx_already_count / All_hx_total_count).toFixed(2) * 100 +
                "%";
            } else {
              sums[column.property] = "";
            }
          }
        });
      });
      sums["customer_area_name"] = "汇总";
      // 显示结果保留两位小数
      Object.keys(sums).forEach((key) => {
        if (typeof sums[key] === "number") {
          sums[key] = sums[key].toFixed(2);
        }
      });
      return Object.keys(sums).map((key) => {
        return sums[key];
      });
    },
  },
};
</script>
<style lang="less" scoped>
.incomesDetial {
  padding: 10px 15px;
  background-color: #fff;
  .summaryheader {
    margin: 0 auto;

    .shareheader_top {
      display: flex;
      flex-wrap: wrap;
    }
  }
}
</style>